package com.chinanet.controller;

import com.chinanet.auth.JwtAuthenticationResponse;
import com.chinanet.auth.JwtToken;
import com.chinanet.auth.JwtTokenUtil;
import com.chinanet.oracle.entry.User;
import com.chinanet.oracle.repository.UserRepository;
import com.chinanet.oracle.service.imp.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private IUserService userService;

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/auth/login", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody User user) throws AuthenticationException {
        System.out.println( user.getAccount()+ ":" + user.getPsw());
        System.out.println("createAuthenticationToken");
        //  @RequestBody JwtAuthenticationRequest authenticationRequest
        final String token = userService.login(user.getAccount(), user.getPsw());
        System.out.println(token);
        // Return the token
        return ResponseEntity.ok(new JwtAuthenticationResponse(token));
    }

    @RequestMapping(value = "/auth/refresh", method = RequestMethod.GET)
    public ResponseEntity<?> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = userService.refreshToken(token);
        if (refreshedToken == null) {
            return ResponseEntity.badRequest().body(null);
        } else {
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
        }
    }
    @RequestMapping(value = "/auth/user", method = RequestMethod.POST)
    public User GetUserByAuthenticationToken(@RequestBody JwtToken token) throws AuthenticationException {
        System.out.println(token);
        String account = new JwtTokenUtil().getUsernameFromToken(token.getToken());
        System.out.println(account);
        return userRepository.findByAccount(account);
    }
}